<template>
  <div class="app-container">
    <div class="tableTimeList">
      <el-row style="margin-bottom: 20px">
        <el-col :span="4" :offset="22">
          <el-checkbox-group v-model="ruleForm.type" @change="checkClick">
            <el-checkbox label='剔除节假日' name="type"></el-checkbox>
          </el-checkbox-group>
        </el-col>
      </el-row>
      <el-table
        :header-cell-style="tableHeaderStyle"
        border
        :data="tableRoleData"
        style="width: 100%"
        max-height="650">
        <el-table-column
          fixed
          prop="role"
          label="成员"
          :show-overflow-tooltip="true"
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          fixed
          prop="jueSeName"
          label="角色"
          align="center"
          :show-overflow-tooltip="true"
          width="100">
        </el-table-column>
        <el-table-column
          fixed
          prop="mode"
          label="投入方式"
          width="110">
          <template slot-scope="scope">
            <el-select v-model="scope.row.mode" @change="typeClick(scope.row)">
              <el-option
                key="2"
                label="平均"
                :value="true">
              </el-option>
              <el-option
                key="1"
                label="自定义"
                :value="false">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          fixed
          label="开始"
          width="150"
        >
          <template slot-scope="scope">
            <el-date-picker
              @change="choseStart(scope.row)"
              style="width: 96%;"
              v-model="scope.row.start"
              type="date"
              :clearable="false"
              :picker-options="pickerOptions_start[`${scope.$index}`]"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column
          fixed
          label="结束"
          width="150">
          <template slot-scope="scope">
            <el-date-picker
              @change="choseEnd(scope.row, scope.$index)"
              style="width: 96%;"
              v-model="scope.row.end"
              :clearable="false"
              :picker-options="pickerOptions_end[`${scope.$index}`]"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column
          fixed
          label="累计投入(人天)"
          width="130">
          <template slot-scope="scope">
            <el-input
                    @input="taskAllChang(scope.row)"
                    type="number"
                    :disabled="!scope.row.mode"
                    v-model.number="scope.row.all">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item,index) of workDays"
          :prop="item.value"
          :label="item.value"
          v-if='item.work || !ruleForm.type[0]'
          width="120">
          <template slot-scope="scope">
            <el-input
              v-if='new Date(scope.row.start).getTime()<=new Date(item.workDate).getTime() && new Date(scope.row.end).getTime()>=new Date(item.workDate).getTime()'
              :disabled="scope.row.mode"
              @input="taskTimeChange(scope.row,item)"
              type="number"
              v-model.number="scope.row[item.value] ">
            </el-input>
            <span v-else></span>
          </template>

        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作">
            <template slot-scope="scope">
              <el-button @click="handleClick(scope.row)" type="text" size="small">删除</el-button>
            </template>
        </el-table-column>
      </el-table>
    </div>


    <user-list style="margin-top: 20px" :choseList="tableRoleData"   :type="'button'" :selectShow="true" @handleChose="userChose"></user-list>
  </div>

</template>

<script>
    import moment from 'moment'
    import {tableHeaderStyle} from '@/utils/constant'
    import UserList from '@/components/userList/index'
    import my_stepbox from '@/components/StepBox/index'
    import {
        http_createObject_userList,
        http_createObject_getRole
    } from '@/api/createObject'
    import {Message} from "element-ui";

    export default {
        name: 'tableList',
        props:{
            nodeId:{
                default:''
            },
            jieStart:{
                default:''
            },
            jieEnd:{
                default:''
            },
            tableTimeList:{
                default () {
                    return []
                }
            }
        },
        data() {
            return {
                tableHeaderStyle: tableHeaderStyle,
                form: {
                    proTypeId: ''
                },
                dialogVisible: false,
                ruleForm: {
                    radio1: 3,
                    radio2: 3,
                    time1: '',
                    time2: '',
                    type: ['剔除节假日',]
                },
                rules: {},
                tableRoleData: [],
                selectOptions: [],
                addValue: [],
                // 流转项目负责人列表
                userList: [],
                userPageSize: 10,
                usertotal: 0,
                userPageCurrent: 0,
                userName: '',
                arr:[],
                pickerOptions_start:{},
                pickerOptions_end:{},
                workDays:[]
            }

        },
        created() {
            this.workDays = this.tableTimeList
        },
        watch:{
            tableRoleData:{
                handler(tableRoleData,oldTableRoleData){

                    // 监听实现 时间可选范围
                    const s = 24*60*60*1000
                    let start = this.getMaxTime( [this.jieStart])
                    let end = this.getMinTime( [this.jieEnd])

                    tableRoleData.forEach((t,i)=>{
                        let start1 = this.getMaxTime( [this.jieStart,t.start])
                        let end1 = this.getMinTime( [this.jieEnd,t.end])
                        this.pickerOptions_start[`${i}`]={
                            disabledDate(time) {
                                return time.getTime() < Date.now() - s || time.getTime() < start ||  time.getTime() > end1
                            }
                        }
                        this.pickerOptions_end[`${i}`]={
                            disabledDate(time) {
                                return time.getTime() < Date.now() - s || time.getTime() < start1 ||  time.getTime() > end
                            }
                        }
                    })

                    // 监听开始时间 和结束时间
                    tableRoleData.forEach(item=>{
                        let workTimes = this.getDayAll(item.start,item.end)
                        let workDayList = this.workDays.map(w=>w.value)
                        let workTimeList = workTimes.filter(wt=>{if(workDayList.indexOf(wt) != -1) return wt})
                        item.workTimes = workTimeList
                    })

                    // 监听实现： 节假日后自动计算人力投入功能
                    tableRoleData.forEach((item,i)=>{
                        // 投入方式：平均
                        if(item.mode == true){
                            if ( item.workTimes.length > 0){
                                item.workTimes.forEach(wt=>{
                                    let ave = item.all/item.workTimes.length
                                    if (ave >2){
                                        Message.closeAll()
                                        Message.warning('每日人天不能大于2')
                                        item[`${wt}`] = 0.00
                                        item.all = 0.00
                                    }else {
                                        // item.all = Number(item.all).toFixed(2)
                                        item[`${wt}`] = Number(ave).toFixed(2)
                                        item.all = this.getNumberTwo(item.all)
                                    }
                                })
                            }else {
                                item.all = '0.00'
                            }

                        // 投入方式： 自定义
                        }else {
                            // if(oldTableRoleData[i].mode  ){
                                let arr =[]
                                item.workTimes.forEach(wt=>{
                                    // item[`${wt}`] = Number(item[`${wt}`]).toFixed(2)
                                    if (item[`${wt}`]  > 2){
                                        Message.closeAll()
                                        Message.warning('每日人天不能大于2')
                                        item[`${wt}`] = 0.00
                                    }else {
                                        item[`${wt}`] = this.getNumberTwo(item[`${wt}`])
                                        arr.push(item[`${wt}`])
                                    }
                                })
                                item.all = (Number(eval(arr.join("+"))).toFixed(2))

                        }

                    })

                },
                immediate: true,
                deep:true
            },





            tableTimeList:{
                handler(newName, oldName) {
                    for(let i in newName){
                        this.tableTimeList[i] = newName[i]
                    }
                },
                // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法，如果设置了false，那么效果和上边例子一样
                immediate: true,
                deep:true
            }
        },
        components: {my_stepbox,UserList},

        computed: {},
        mounted() {
            this.getUserLsit()
            this.getRoleList()
            this.checkClick("剔除节假日")
        },
        methods: {
            getMaxTime(params){
                let times = params.filter((s)=>{if(s != null && s != '' ) return s})
                return new Date(new Date(new Date(Math.max.apply(null,times.map((e=>new Date(e))))).getTime()).toLocaleDateString())
            },
            getMinTime(params){
                let times = params.filter((s)=>{if(s != null && s != '' ) return s})
                return new Date(new Date(new Date(Math.min.apply(null,times.map((e=>new Date(e))))).getTime()).toLocaleDateString())
            },
            getNumberTwo(num){
                return Number(num.toString().match(/^\d+(?:\.\d{0,2})?/));
            },
            userChose(val){
                var flag
                if (this.tableRoleData.length) {
                    this.tableRoleData.some((item, index) => {
                        if (item.roleId == val.userId) {
                            this.$message('已添加该成员')
                            flag = true
                            return true
                        }
                    })
                }
                if (!flag) {
                    if (val.selectValue) {
                        var roleName
                        this.selectOptions.forEach((item,index)=>{
                            if(val.selectValue == item.id){
                                roleName = item.roleName
                            }
                        })
                        this.tableRoleData.push({
                            jueSeName:  roleName,
                            jueSe: val.selectValue,
                            roleId: val.userId,
                            role: val.userName,
                            mode: true,
                            start: '',
                            end: '',
                            all: '',
                            userId: val.userId
                        })
                    } else {
                        this.$message('请选择项目角色再添加')
                    }

                }
            },
            handleClick(val){
                this.tableRoleData.forEach((item,index)=>{
                    if(val.roleId == item.roleId){
                        this.tableRoleData.splice(index,1)
                    }
                })
            },
            // 全部提交
            submitForm(formName) {
                var obj = {
                    proAssignmentList: [],
                    proPlanHoursList: []
                }
                this.tableRoleData.forEach((item, index) => {
                    obj.proAssignmentList.push({
                        "inputHours": item.start && item.end && new Date(item.end) >= new Date(item.start) ? item.all : '',
                        "inputEnd": item.end,
                        "inputStart": item.start,
                        "inputType": item.mode ? 2 : 1,
                        "nodeEnd": this.jieEnd,
                        "nodeId": this.nodeId,
                        "nodeStart": this.jieStart,
                        "proId": this.$route.query.id,
                        "proroleId": item.jueSe,
                        "userId": item.roleId
                    })
                    var timeList = []
                    Object.keys(item).some((it, ind) => {
                        if (it.includes('.')) {
                            timeList.push(it)
                        }
                    })
                    timeList.some((it, ind) => {
                        this.tableTimeList.map((itt, indd) => {
                            if (it == itt.value) {
                                if (this.ruleForm.type.length) {
                                    if (itt.work) {
                                        obj.proPlanHoursList.push({
                                            "inputHours": item[it],
                                            "nodeId": this.nodeId,
                                            "planDate": itt.workDate,
                                            "proId": this.$route.query.id,
                                            "proroleId": item.jueSe,
                                            "userId": item.roleId
                                        })
                                    }
                                } else {
                                    obj.proPlanHoursList.push({
                                        "inputHours": item[it],
                                        "nodeId": this.nodeId,
                                        "planDate": itt.workDate,
                                        "proId": this.$route.query.id,
                                        "proroleId": item.jueSe,
                                        "userId": item.roleId
                                    })
                                }
                            }
                        })
                    })
                })

              return obj

            },
            // 时间框点击
            taskTimeChange(val,self) {
                 val[self.value] = Math.round(val[self.value]*100)/100
                if(val[self.value]>=0){
                    val.all = 0
                    this.tableTimeList.forEach((item, index) => {
                        if (new Date(val.start).getTime() <= new Date(item.workDate).getTime() && new Date(val.end).getTime() >= new Date(item.workDate).getTime()) {
                            if (item.work || !this.ruleForm.type[0]) {
                                if (Number(val[item.value])) {
                                    val.all += Number(val[item.value])
                                }
                            }
                        }
                    })
                    val.all = Math.round(val.all*100)/100

                }else{
                    val[self.value] = ''
                    this.$message('请输入大于零的数')
                }

            },
            // all框点击
            taskAllChang(val) {
                if (val.mode) {
                    if (val.all >= 0) {
                        val.all = Math.round(val.all*100)/100
                        var flag = 0
                        var timeList = []
                        this.tableTimeList.forEach((item, index) => {
                            if (new Date(val.start).getTime() <= new Date(item.workDate).getTime() && new Date(val.end).getTime() >= new Date(item.workDate).getTime()) {
                                if (item.work || !this.ruleForm.type[0]) {
                                    flag++
                                    var string = item.workDate.replace('-', '.')
                                    timeList.push(string.replace('-', '.'))
                                }
                            }
                        })
                        timeList.forEach((item, index) => {
                            val[item] =  Math.round(val.all / flag * 100 )/ 100
                        })
                    }else{
                            this.$message('请输入大于零的数')
                            val.all = ''
                    }
                }
            },
            // 是否剔除节假日
            checkClick( val ) {
                console.log("val:" ,val)
                console.log("ruleForm.type:" ,this.ruleForm.type)
                // 放假前
                if (val[0] == null){
                    this.workDays = this.tableTimeList
                    let others = this.tableTimeList.filter(item=>item.work == false)
                    this.tableRoleData.forEach(item=>{
                        others.forEach(o=>{
                            this.$set(item, o.value, '')
                            this.$set(item, 'timeLength', this.workDays.length)
                            // item[o.value] = ''
                            // item.all = this.workDays.length
                            // item.timeLength = this.workDays.length
                        })
                    })
                // 放假后
                }else {
                    this.workDays = this.tableTimeList.filter(item=>item.work == true)
                    console.log("this.workDays :",this.workDays )
                    let others = this.tableTimeList.filter(item=>item.work == false)
                    console.log("others: ", others )
                    console.log("this.tableRoleData: ", this.tableRoleData )
                    this.tableRoleData.forEach(item=>{
                        others.forEach(o=>{
                            this.$set(item, o.value, '')
                            this.$set(item, 'timeLength', this.workDays.length)
                        })
                    })
                }




                    // this.tableRoleData.map((value, ind) => {
                    //     console.log("value",value)
                    //     if(value.mode){
                    //         value.all = Math.round(value.all*100)/100
                    //         var flag = 0
                    //         var timeList = []
                    //         this.tableTimeList.forEach((item, index) => {
                    //             if (new Date(value.start).getTime() <= new Date(item.workDate).getTime() && new Date(value.end).getTime() >= new Date(item.workDate).getTime()) {
                    //                 if (item.work || !this.ruleForm.type[0]) {
                    //                     flag++
                    //                     var string = item.workDate.replace('-', '.')
                    //                     timeList.push(string.replace('-', '.'))
                    //                 }
                    //             }
                    //         })
                    //         this.$nextTick(()=>{
                    //             timeList.forEach((item, index) => {
                    //                 this.$set(value,item,Math.round(value.all / flag * 100 )/ 100)
                    //             })
                    //         })
                    //
                    //     }else{
                    //         value.all = 0
                    //         console.log("tableTimeList",tableTimeList)
                    //         this.tableTimeList.forEach((item, index) => {
                    //             if (new Date(value.start).getTime() <= new Date(item.workDate).getTime() && new Date(value.end).getTime() >= new Date(item.workDate).getTime()) {
                    //                 if (item.work || !this.ruleForm.type[0]) {
                    //                     if (Number(value[item.value])) {
                    //                         value.all += Number(value[item.value])
                    //                     }
                    //                 }
                    //             }
                    //         })
                    //         value.all = Math.round(value.all*100)/100
                    //     }
                    // })





                // this.tableRoleData.some((it, ind) => {
                //     it.all =  Math.round(it.all* 100 )/ 100
                // })
            },


            // 投入方式选择
            typeClick(val) {
                // Object.keys(val).forEach((item, index) => {
                //     if (item != 'roleId' && item != 'role' && item != 'mode' && item != 'jueSeName'&& item != 'jueSe') {
                //         val[item] = ''
                //     }
                // })
            },
            oninput(e) {
                // 通过正则过滤小数点后两位
                e.target.value = (e.target.value.match(/^\d*(\.?\d{0,2})/g)[0]) || null

                // console.log('e',e.target.value)
            },

            // 开始时间选择
            choseStart(value) {
                if (new Date(value.start) < new Date(this.jieStart).getTime()) {
                    this.$message('选择日期不在节点范围')
                    value.start = ''
                }
                if (new Date(value.start) > new Date(this.jieEnd).getTime()) {
                    this.$message('选择日期不在节点范围')
                    value.start = ''
                }
                this.$nextTick(()=>{
                    this.tableTimeList.forEach((item,index)=>{
                        this.tableRoleData.map((it,ind)=>{
                            if(value.start&&value.end){
                                // moment(item.value).isBetween(value.start, value.end, null, '[]')
                                if(!(moment(item.value).isBetween(value.start, value.end, null, '[]'))){
                                    var string = item.value.replace('-','.').replace('-','.')
                                    it[string] = ''
                                }
                            }
                        })
                    })
                    if(value.mode){
                        value.all = Math.round(value.all*100)/100
                        var flag = 0
                        var timeList = []
                        this.tableTimeList.forEach((item, index) => {
                            if (new Date(value.start).getTime() <= new Date(item.workDate).getTime() && new Date(value.end).getTime() >= new Date(item.workDate).getTime()) {
                                if (item.work || !this.ruleForm.type[0]) {
                                    flag++
                                    var string = item.workDate.replace('-', '.')
                                    timeList.push(string.replace('-', '.'))
                                }
                            }
                        })
                        this.$nextTick(()=>{
                            timeList.forEach((item, index) => {
                                this.$set(value,item,Math.round(value.all / flag * 100 )/ 100)
                            })
                        })

                    }else{
                        value.all = 0
                        this.tableTimeList.forEach((item, index) => {
                            if (new Date(value.start).getTime() <= new Date(item.workDate).getTime() && new Date(value.end).getTime() >= new Date(item.workDate).getTime()) {
                                if (item.work || !this.ruleForm.type[0]) {
                                    if (Number(value[item.value])) {
                                        value.all += Number(value[item.value])
                                    }
                                }
                            }
                        })
                        value.all = Math.round(value.all*100)/100
                    }
                })

            },

            // 结束时间选择
            choseEnd(value, currIndex) {
                if (new Date(value.end) > new Date(this.jieEnd).getTime()) {
                    this.$message('选择日期不在节点范围')
                    value.end = ''
                }
                if (new Date(value.end) < new Date(this.jieStart).getTime()) {
                    this.$message('选择日期不在节点范围')
                    value.end = ''
                }
                // new Date(val.start).getTime() <= new Date(item.workDate).getTime() && new Date(val.end).getTime() >= new Date(item.workDate).getTime()
                this.$nextTick(()=>{
                    const currItem = this.tableRoleData[currIndex]
                    // this.tableTimeList.forEach((item,index)=>{
                    //     // this.tableRoleData.map((it,ind)=>{
                    //     //     if(value.start&&value.end){
                    //     //         // moment(item.value).isBetween(value.start, value.end, null, '[]')
                    //     //         if(moment(item.value).isBetween(value.start, value.end, null, '[]')){

                    //     //         }else{
                    //     //             var string = item.value.replace('-','.').replace('-','.')
                    //     //             it[string] = ''
                    //     //         }
                    //     //     }
                    //     // })
                    // })
                    this.tableTimeList.map(el => currItem[`${el.value}`] = currItem[`${el.value}`] || '')
                    if(value.mode){
                        value.all = Math.round(value.all*100)/100
                        var flag = 0
                        var timeList = []
                        this.tableTimeList.forEach((item, index) => {
                            if (new Date(value.start).getTime() <= new Date(item.workDate).getTime() && new Date(value.end).getTime() >= new Date(item.workDate).getTime()) {
                                if (item.work || !this.ruleForm.type[0]) {
                                    flag++
                                    var string = item.workDate.replace('-', '.')
                                    timeList.push(string.replace('-', '.'))
                                }
                            }
                        })
                        this.$nextTick(()=>{
                            timeList.forEach((item, index) => {
                                this.$set(value,item,Math.round(value.all / flag * 100 )/ 100)
                            })
                        })

                    }else{
                        value.all = 0
                        this.tableTimeList.forEach((item, index) => {
                            if (new Date(value.start).getTime() <= new Date(item.workDate).getTime() && new Date(value.end).getTime() >= new Date(item.workDate).getTime()) {
                                if (item.work || !this.ruleForm.type[0]) {
                                    if (Number(value[item.value])) {
                                        value.all += Number(value[item.value])
                                    }
                                }
                            }
                        })
                        value.all = Math.round(value.all*100)/100
                    }
                })
                // this.checkClick(value)

            },
            // 人员表
            getUserLsit() {
                http_createObject_userList({
                    pageNum: this.userPageCurrent,
                    pageSize: this.userPageSize,
                    userName: this.userName
                }).then((res) => {
                    if (res.success) {
                        this.userList = res.data.records
                        this.usertotal = res.data.total
                        // 测试
                        // this.tableRoleData.push({
                        //   roleId : this.userList[1].userId,
                        //   role: this.userList[1].userName,
                        //   mode: true,
                        //   start: '',
                        //   end: '',
                        //   all: ''
                        // })
                        // this.tableRoleData.push({
                        //   roleId : this.userList[2].userId,
                        //   role: this.userList[2].userName,
                        //   mode: false,
                        //   start: '',
                        //   end: '',
                        //   all: ''
                        // })
                        if (this.usertotal) {
                            if (this.path) {
                                this.form.managerName = this.userList[0].userName
                                this.form.proManager = this.userList[0].userId
                            } else {
                                this.userList.forEach((item, index) => {
                                    if (this.form.proManager == item.userId) this.form.managerName = item.userName
                                })
                            }
                        }
                    } else {
                        this.$message(res.message)
                    }
                })
            },
            // 人员角色列表
            getRoleList() {
                http_createObject_getRole().then((res)=>{
                    this.selectOptions = res.data
                })
            },
            // 添加角色
            addRole(val) {

            },
            handleSizeChange(val) {
                this.userPageCurrent = val
                this.getUserLsit()
            },
            handleCurrentChange(val) {
                this.userPageCurrent = val
                this.getUserLsit()
            },
            getDayAll(starDay, endDay) {
                let arr = [];
                let dates = [];

                // 设置两个日期UTC时间
                let db = new Date(starDay);
                let de = new Date(endDay);

                // 获取两个日期GTM时间
                let s = db.getTime() - 24 * 60 * 60 * 1000;
                let d = de.getTime() - 24 * 60 * 60 * 1000;

                // 获取到两个日期之间的每一天的毫秒数
                for (let i = s; i <= d;) {
                    i = i + 24 * 60 * 60 * 1000;
                    arr.push(parseInt(i))
                }

                // 获取每一天的时间  YY-MM-DD
                for( let j in arr ){
                    let time = new Date(arr[j]);
                    let year = time.getFullYear(time);
                    let mouth = (time.getMonth() + 1)>=10?(time.getMonth() + 1):('0'+(time.getMonth() + 1));
                    let day = time.getDate()>=10?time.getDate():('0'+time.getDate());
                    let YYMMDD = year + '.' + mouth + '.' + day;
                    dates.push(YYMMDD)
                }
                return dates
            }

        }
    }
</script>

<style lang="scss" scoped>

  .notes {
    font-size: 12px;
    color: #888888;
    line-height: 30px;
    margin-bottom: 22px
  }


  .el-button + .el-button {
    margin-left: 0px;
  }
  .tableTimeList{
    ::v-deep .el-input__inner{
        padding: 0 0 0 15px;
    }
  }
</style>

<style lang="less" scoped>

    .el-input {
        /deep/ .el-input__inner {
            padding-left: 30px;
        }
    }



</style>



